<template>
    <div class="chat-container fixed">
        <div class="dialog-header">
          <slot name="header">
            <h3 class="dialog-title">智能聊天系统</h3>
          </slot>
          <div class="buttons">
            <img src="../assets/img/module5/dialog/guanbi.png" @click="closeChatModule" alt="关闭" class="button-icon" />
          </div>
        </div>

        <div class="chat-content">
            <!-- 显示欢迎语或提示信息 -->
            <div v-if="chatMessages.length === 0" class="welcome-message">
                <p>欢迎来到智能聊天系统！</p>
                <p>请输入您的问题。</p>
            </div>
            <!-- 显示聊天记录 -->
            <div v-else>
                <div v-for="(message, index) in chatMessages" :key="index" class="chat-message">
                    <div :class="{ 'user-message': message.isUser, 'bot-message': !message.isUser }">
                        <template v-if="message.isUser">
                            <div class="message-content">
                                <p v-html="formatMessage(message.content)"
                                    :class="{ 'loading-text': message.isLoading }"></p>
                            </div>
                            <img :src="message.avatar" alt="avatar" class="avatar" />
                        </template>

                        <template v-else>
                            <img :src="message.avatar" alt="avatar" class="avatar" />
                            <div class="message-content">
                                <p v-html="formatMessage(message.content)"
                                    :class="{ 'loading-text': message.isLoading }"></p>
                                <!-- <template v-if="!message.isLoading">
                                    <el-button v-if="message.content" type="primary"
                                        @click="saveContent(message.messageId)" class="save-AI-button">
                                        复制
                                    </el-button>
                                </template> -->
                            </div>
                        </template>
                    </div>
                </div>
            </div>
        </div>

        <!-- 输入区域 -->
        <div class="chat-input-area">
            <el-input v-model="userInput" type="textarea" :rows="3" placeholder="请输入您的问题..." :disabled="isChatting"
                class="chat-textarea" />
            <el-button type="primary" :disabled="!userInput.trim() || isChatting" @click="sendUserMessage"
                class="send-button">
                {{ isChatting ? '正在处理...' : '发送' }}
            </el-button>
        </div>
    </div>
</template>

<script>
import axios from 'axios';
import userAvatar from '@/assets/img/avatar/userAvatar.png';
import gptAvatar from '@/assets//img/avatar/gptAvatar.png';

const baseApi = process.env.NODE_ENV === 'production' ? 
'/api' 
:
'http://192.168.0.135:30027';
// process.env.VUE_APP_REMOTE_API_MODULE1;

export default {
    data() {
        return {
            userAvatar: userAvatar,
            botAvatar: gptAvatar,
            chatMessages: [],
            userInput: '',
            isChatting: false,
            isChatMode: false, // 默认不是聊天模式
            isEditing: false, // 控制编辑状态
            selectedRow: null, // 当前选中的行
        };
    },
    methods: {
        closeChatModule() {
            // 关闭聊天模块
            this.$emit('close'); // 向父组件发送关闭事件
        },
        // 发送用户消息
        async sendUserMessage() {
            if (!this.userInput.trim()) return;

            this.chatMessages.push({
                isUser: true,
                avatar: this.userAvatar,
                content: this.userInput,
                messageId: Date.now()
            });

            const history = [
                {
                role: 'system',
                content:
                    '你是龙智低空管控助手，专注于解答与低空空域管理相关的问题。用户可能需要如下帮助：“空域使用规范”、“空域使用条件”、“空域申报流程”、“航线申请步骤”等。请始终以专业、简洁的方式提供解答。'
                },
                ...this.chatMessages
                .filter(msg => !msg.isLoading)
                .map(msg => ({
                    role: msg.isUser ? 'user' : 'assistant',
                    content: msg.content
                }))
            ];

            const requestData = {
                message: this.userInput,
                history: history.slice(0, -1), // 不包含最新的用户消息，因为它已经在 message 字段中了
                filesId: []
            };

            this.isChatting = true;
            this.chatMessages.push({
                isUser: false,
                avatar: this.botAvatar,
                isLoading: true,
                content: "正在思考中...",
                messageId: Date.now()
            });

            try {
                const response = await axios.post(`${baseApi}/chat/aliBailian`, requestData);
                if (response.data.code === 0) {
                    await this.handleStreamResponse(response.data.data);
                } else {
                    throw new Error(response.data.msg || '请求失败');
                }
            } catch (error) {
                console.error('Error:', error);
                this.$message.error(error.message || '发送消息失败，请重试');
            } finally {
                this.isChatting = false;
            }

            this.userInput = ''; // 清空输入框
        },

        // 格式化消息内容
        formatMessage(text) {
            if (!text) return '';
            return text.replace(/\n/g, '<br>');
        },

        // 逐字显示响应内容
        async handleStreamResponse(responseText) {
            const loadingMessageIndex = this.chatMessages.length - 1;
            let displayedResponse = '';

            this.$set(this.chatMessages[loadingMessageIndex], 'content', '');

            for (let i = 0; i < responseText.length; i++) {
                displayedResponse += responseText[i];
                this.$set(this.chatMessages[loadingMessageIndex], 'content', displayedResponse);
                await new Promise(resolve => setTimeout(resolve, 30));
            }

            this.$set(this.chatMessages[loadingMessageIndex], 'isLoading', false);
        },

        // 复制内容到剪贴板
        async saveContent(messageId) {
            const message = this.chatMessages.find(msg => msg.messageId === messageId && !msg.isUser);
            if (!message) return;

            try {
                await navigator.clipboard.writeText(message.content);
                this.$message.success("已复制到剪贴板！");
            } catch (err) {
                console.error("复制失败:", err);
                this.$message.error("复制失败，请重试");
            }
        },

        // 切换聊天模式
        toggleChatMode() {
            this.isChatMode = !this.isChatMode;
            if (this.isChatMode) {
                this.chatMessages = [];
                this.isChatting = false;
                this.userInput = '';
            }
        },

        // 设置选中的行ID
        setSelectedRow(rowId) {
            this.selectedRow = rowId;
        },
    }
};
</script>

<style scoped>
/* 聊天对话框样式 */
.chat-container {
  padding: 0;
  background-color: #f5f5f5dc;
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  width: 100%;
  max-width: 400px; /* 设置对话框最大宽度 */
  height: 50vh; /* 设置对话框最大高度 */
  margin: auto;
  z-index: 1000;
}

.dialog-header {
  display: flex;
  width: 100%;
  height: 3rem;
  justify-content: center;
  align-items: center;
  position: relative;
  background-image: url("../assets/img/module5/dialog/headbar.png"), url("../assets/img/module5/dialog/dialogtopimg1.png"), url("../assets/img/module5/dialog/dialogtopimg2.png");
  background-position: center, center, center;
  background-size: cover, auto, auto;
  background-repeat: no-repeat, no-repeat, no-repeat;
  /* border-top-left-radius: 10px;
  border-top-right-radius: 10px; */
}

.dialog-title {
  font-size: 1.5rem;
  color: #ffffff;
  text-align: center;
  margin: 0;
}

.buttons {
  position: absolute;
  right: 2%;
}

.button-icon {
  width: 40px;
  height: 40px;
  cursor: pointer;
}

/* 显示消息内容的区域 */
.chat-content {
  height: 100%;
  overflow-y: scroll;
  flex-grow: 1;
  padding-bottom: 10px;
  margin-left: 10px;
  margin-top: 5px;
}

.welcome-message {
  text-align: center;
  /* 居中显示 */
  color: #0c0c0c;
  /* 灰色文本 */
  font-size: 16px;
  margin-top: 20vh;
}

/* 用户和机器人消息样式 */
.chat-message {
  display: flex;
  margin-bottom: 10px;
}

.user-message {
  align-self: flex-end;
  width: 100%;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.bot-message {
  align-self: flex-start;
  width: 100%;
  display: flex;
  justify-content: flex-start;
  gap: 10px;
}

/* 用户和机器人头像 */
.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

/* 消息内容 */
.message-content {
  max-width: 70%;
  background: #f0f0f0;
  padding: 5px 10px;
  border-radius: 8px;
  word-break: break-word;
}

/* 输入框区域 */
.chat-input-area {
  display: flex;
  gap: 10px;
  margin-top: 20px;
  align-items: flex-start;
  margin-left: 10px;
  margin-bottom: 5px;
}

/* 输入框 */
.chat-textarea {
  flex-grow: 1;
}

/* 发送按钮 */
.send-button {
  width: 100px;
  height: 40px;
}

/* 右下角位置设置 */
.chat-container.fixed {
  position: fixed;
  bottom: 3%;
  right: 2%;
  z-index: 9999;
}

</style>